package com.glasses.spectrum;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.application.Application;
import javax.faces.context.FacesContext;

/**
 *
 * @author Jean-Luc Burot
 * @since 2014-12-13
 * @version 1
 */
public class ManagedPropertyProducer {
    @Produces @ManagedPropertyInject @Dependent
    public String getStringManagedPropertyInject(InjectionPoint injectionPoint) {
        return (String) getObjectManagedPropertyInject(injectionPoint, String.class);
    }
    
    private Object getObjectManagedPropertyInject(InjectionPoint injectionPoint, Class expectedType) {
        String value = injectionPoint.getAnnotated().getAnnotation(ManagedPropertyInject.class).value();
        FacesContext context = FacesContext.getCurrentInstance();
        Application application = context.getApplication();
        ExpressionFactory ef = application.getExpressionFactory();
        ELContext elContext = context.getELContext();
        ValueExpression ve = ef.createValueExpression(elContext, value, expectedType);
        return ve.getValue(elContext);
    }
}
